package com.quzi.kettle.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import android.os.Handler;
import android.util.Log;


public class SocketRequest {
	
	private String TAG = "SocketChar";
	
	private Handler handler;
	private static SocketRequest instance;
	public static SocketRequest getInstance(String URL, int port, Handler handler){
		if(instance == null){
			instance = new SocketRequest(URL, port, handler);
		}
		return instance;
	}
	private SocketRequest(String url, int port, Handler handler){
		Log.d(TAG,"初始化 "+url+"  "+port);
		setURL(url);
		setPort(port);
		this.handler = handler;
	}
	
	
	private IoSession session;
	ClientHandler clientHandler;

	String Target_Url = "192.168.6.8";
	int Target_Comm = 20088;
	
	
	public void setURL(String url){
		this.Target_Url = url;
	}
	
	public void setPort(int port){
		this.Target_Comm = port;
	}
	
	public boolean connection2Service() {
		boolean result = true;
		boolean stopReconnection = true ; 
		int Reconnection_Times = 0;
		NioSocketConnector connector = new NioSocketConnector();
		while (stopReconnection) {

			connector.getFilterChain().addLast("logger", new LoggingFilter());

//			connector.getFilterChain().addLast("codec",
//					new ProtocolCodecFilter(new MideaCodecFactory()));
			
			if( clientHandler == null ){
				clientHandler = new ClientHandler();
			}
			
			connector.setHandler(clientHandler);

			ConnectFuture future1 = connector.connect(new InetSocketAddress(Target_Url,
					Target_Comm));

			future1.awaitUninterruptibly();
			
			session = future1.getSession();
			if(session.isConnected()){
				stopReconnection = false ;
			}
			
			Reconnection_Times++;
			if (Reconnection_Times > 30) {
				result = false;
				stopReconnection = false ;
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
		return result;
	}
	
	
	/**
	 * HelloServer的处理逻辑
	 * 
	 */
	class ClientHandler implements IoHandler {
		

		public ClientHandler(){
			
		}

		@Override
		public void exceptionCaught(IoSession arg0, Throwable arg1)
				throws Exception {
			Log.i(TAG, "Exception   "+arg1);
		}

		@Override
		public void messageReceived(IoSession arg0, Object message)
				throws Exception {
			String str = message.toString();
			Log.d(TAG, ""+str);
			handler.obtainMessage(0, str).sendToTarget();

		}

		@Override
		public void messageSent(IoSession arg0, Object arg1) throws Exception {
			Log.i(TAG, "sessionSend "+arg1.toString());
		}

		@Override
		public void sessionClosed(IoSession arg0) throws Exception {
			Log.i(TAG, "sessionClosed");
		}

		@Override
		public void sessionCreated(IoSession arg0) throws Exception {
			Log.i(TAG, "sessionCreated");
		}

		@Override
		public void sessionIdle(IoSession arg0, IdleStatus arg1)
				throws Exception {
			Log.i(TAG, "sessionIdle");
		}

		@Override
		public void sessionOpened(IoSession arg0) throws Exception {
			Log.i(TAG, "sessionOpened");
		}
		
	}


	public void writeCMD(byte[] datas) {
		// TODO Auto-generated method stub
		if(session != null){
			session.write(IoBuffer.wrap(datas));
		}else{
			Log.d(TAG,"  session == null");
		}
	}
	
	public int sendPacket(byte[] b) {
		
		try {
		InetAddress address = InetAddress.getByName("255.255.255.0");
				
		DatagramSocket socket = new DatagramSocket(6444);
		
		DatagramPacket packet = new DatagramPacket(b,b.length,address,6444);
		
		
		socket.send(packet);
		
		socket.disconnect();
		socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	
	public void sendUDP(){
		NioDatagramConnector connector = new NioDatagramConnector();
		if( clientHandler == null ){
			clientHandler = new ClientHandler();
		}
		connector.setHandler( new ClientHandler() );
		ConnectFuture connFuture = connector.connect( new InetSocketAddress("255.255.255.255", 9999 ));
	

		connFuture.addListener( new IoFutureListener(){
            public void operationComplete(IoFuture future) {
                ConnectFuture connFuture = (ConnectFuture)future;
                if( connFuture.isConnected() ){
                    session = future.getSession();
                    try {
                        sendData();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {

                }
            }
        });
		
	}

	private void sendData() throws InterruptedException {
	    for (int i = 0; i < 30; i++) {
	        long free = Runtime.getRuntime().freeMemory();
	        IoBuffer buffer = IoBuffer.allocate(8);
	        buffer.putLong(free);
	        buffer.flip();
	        session.write(buffer);
	        try {
	            Thread.sleep(1000);
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	            throw new InterruptedException(e.getMessage());
	        }
	    }
	}
	
//监听
	 public void MemoryMonitorTest() throws IOException {  
		  
	        NioDatagramAcceptor acceptor = new NioDatagramAcceptor();//创建一个UDP的接收器  
	        acceptor.setHandler(clientHandler);;//设置接收器的处理程序  
	  
	         Executor threadPool = Executors.newFixedThreadPool(1500);//建立线程池  
	        acceptor.getFilterChain().addLast("exector", new ExecutorFilter(threadPool));  
	        acceptor.getFilterChain().addLast("logger", new LoggingFilter());  
	  
	        DatagramSessionConfig dcfg = acceptor.getSessionConfig();//建立连接的配置文件  
	        dcfg.setReadBufferSize(4096);//设置接收最大字节默认2048  
	        dcfg.setReceiveBufferSize(1024);//设置输入缓冲区的大小  
	        dcfg.setSendBufferSize(1024);//设置输出缓冲区的大小  
	        dcfg.setReuseAddress(true);//设置每一个非主监听连接的端口可以重用  
	          
	        acceptor.bind(new InetSocketAddress(9999));//绑定端口  
	    }  
	 
	 
}
